package cn.virens.web.common;

import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;

import cn.virens.database.common.BaseService;
import cn.virens.util.RequestUtil;
import cn.virens.util.page.JqGridRequest;
import cn.virens.util.shiro.Permission;

/**
 * 通用控制器-JqGrid
 * 
 * @文件 :BaseJqGridController.java
 * @作者 :cn.loioi
 * @创建时间 :2016年10月13日 下午1:10:43
 */
public abstract class BaseJqGridController<T, S extends BaseService<T>> extends AbstractTableController<T, BaseService<T>> {

	public BaseJqGridController(String baseTemplateUrl, String identity, S baseService) {
		super(baseTemplateUrl, identity, baseService);
	}

	public BaseJqGridController(String baseTemplateUrl, S baseService) {
		super(baseTemplateUrl, baseService);
	}

	/**
	 * 获取数据接口
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("list.json")
	public Model list(HttpServletRequest request, Model model) throws Exception {
		checkPermission(request, Permission.VIEW.parts(_identity));// 检查用户的权限是否可以访问
		// 执行正常操作
		PageInfo<?> page = getData(request, new JqGridRequest(request));

		if (page.getList() != null && page.getList().size() > 0) {
			model.addAttribute("success", true);
			model.addAttribute("records", page.getTotal());
			model.addAttribute("page", page.getPageNum());
			model.addAttribute("total", page.getPages());
			model.addAttribute("rows", page.getList());
			return renderSuccess(null, model, "加载成功");
		} else {
			return renderFail(model, "没有数据");
		}
	}

	@Override
	protected void savePageInfo(HttpServletRequest request, Model model) {
		model.addAttribute("page", RequestUtil.getValueInt(request, "page", 1));
		model.addAttribute("rows", RequestUtil.getValueInt(request, "rows", 20));
	}
}
